package com.red.wood.module.api.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import net.sf.json.JSONObject;

@RestController
@RequestMapping("/interface")
public class InterfaceTestController {

	private static final Log log = LogFactory.getLog(InterfaceTestController.class);
	
	@Autowired
	private RestTemplate restTemplate;
	
	@GetMapping(value = "/interfaceTest")
	public String interfaceTest(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			String url = request.getParameter("url");
			json = JSONObject.fromObject(request.getParameter("paraObj"));
			
			log.info("请求参数："+json);
			
			HttpHeaders headers = new HttpHeaders();
			MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
			headers.setContentType(type);
			headers.add("Accept", MediaType.APPLICATION_JSON.toString());
			
			HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
			
			String result = restTemplate.postForObject(url,formEntity, String.class);
			json = JSONObject.fromObject(result);
			json.put("data", json.get("data"));//格式转换
		}catch(Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		}
		return json.toString();
	}
}